package com.group2.bankonline.utils;

import com.group2.bankonline.pojo.Personinfo;
import io.jsonwebtoken.*;
import java.util.Date;

public class MyJWT {
    //外部签名带的密钥
    private static long time = 1000*60*60*24;
    //1.生成令牌:三部分-header-payload-signature
    public static String getToken(Personinfo personinfo){
        String token = "";
        //JWT构造器
        JwtBuilder jwtBuilder = Jwts.builder();
        //JWT构造器生成token
        token = jwtBuilder
                //设置header
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //设置payload（传输自定义内容）
                .claim("realname",personinfo.getRealname())
                .claim("telephone",personinfo.getTelephone())
                .claim("id",personinfo.getId())
                .claim("sex",personinfo.getSex())
                .claim("birthday",personinfo.getBirthday())
                //设置token的有效期24h
                .setExpiration(new Date(System.currentTimeMillis()+time))
                //设置签名与签名算法
                .signWith(SignatureAlgorithm.HS256,"Group2")
                //连接三部分
                .compact();
        return  token;
    }
    //2.校验令牌
    public static boolean checkToken(String token){
        JwtParser jwtParser = Jwts.parser();
        try {
            //校验token
            Jws<Claims> claimsJws = jwtParser.setSigningKey("Group2").parseClaimsJws(token);
            claimsJws.getBody();
            return true;
        }catch (Exception ex){
            return false;
        }
    }

    //获取token内的携带的用户名信息
    public static String getNameByToken(String token){
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey("Group2").parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("realname");
    }

    public static Personinfo getPersonByToken(String token){
        //反编译获取token中的用户信息
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey("Group2").parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        //将值取出封装到AccountVo
        Personinfo personinfo = new Personinfo();
        personinfo.setId((Integer) claims.get("id"));
        personinfo.setRealname((String) claims.get("realName"));
        personinfo.setTelephone((String) claims.get("telephone"));
        personinfo.setBirthday((String) claims.get("birthday"));
        personinfo.setSex((String) claims.get("sex"));
        return personinfo;
    }
}
